﻿using GraphProcessor;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class IDGenerateNode : BaseNode
    {
        [SerializeField]
        private string graphGUID;
        protected override void OnClear()
        {
            base.OnClear();
            this.processNum = 0;
        }
        
        private byte processNum;
        protected long GenerateID()
        {
            this.CheckGUIDLong();
            if (this.GUIDLong == 0)
            {
                this.GUIDLong = IdGenerater.Instance.GenerateIntTick() << 8;
                EditorUtility.SetDirty(this.graph);
            }
            return this.GUIDLong + processNum++;
        }
        
        protected int GenerateIDInt()
        {
            this.CheckGUIDLong();
            if (this.GUIDLong == 0 || this.GUIDLong > IdGenerater.Mask32bit)
            {
                this.GUIDLong = IdGenerater.Instance.GenerateIntTick2() & IdGenerater.Mask32bit;
                
                // 新生成的ID要保证LondIDToInt 后为正 内部有左移8位，所以在右数24位为0
                this.GUIDLong &= 0x7FFFFF;
                
                EditorUtility.SetDirty(this.graph);
            }
            return LondIDToInt2(this.GUIDLong);
        }

        // 注意此方法的位移8位后空出的8位并未使用，但此方法不可修改，已被序列化，若有需求可以使用这8位做记录
        public static int LondIDToInt2(long id)
        {
            return (int)(id & IdGenerater.Mask31bit);
        }
        
        private void CheckGUIDLong()
        {
            var rPath = AssetDatabase.GetAssetPath(this.graph);
            var nGraphGUID = AssetDatabase.AssetPathToGUID(rPath);
            if (string.IsNullOrEmpty(this.graphGUID) || this.graphGUID != nGraphGUID)
            {
                this.graphGUID = nGraphGUID;
                this.GUIDLong = 0;
                EditorUtility.SetDirty(this.graph);
            }
        }
    }
}